<template>
	<div class="app-container">
		<el-row type="flex" class="row-bg" justify="end" v-if="$store.state.user.perm.includes('207')">
			<el-button class="filter-item" size="mini" style="margin-left: 10px;" @click="add" type="primary" icon="el-icon-plus">{{$t('role.add')}}</el-button>
		</el-row>
		<el-collapse>
			<el-collapse-item>
				<div slot="title">
					&nbsp;&nbsp;&nbsp;{{$t('role.click_filter')}}&nbsp;&nbsp;&nbsp;<i class="icon iconfont icon-filter" style="font-size: 10px"></i>
				</div>
				<el-form :inline="true" :model="q" class="demo-form-inline query" label-position="left">
					<el-form-item :label="$t('role.operator')">
						<el-input v-model="q.email" :placeholder="$t('role.operator')" prefix-icon="el-icon-edit"></el-input>
					</el-form-item>
					<el-form-item :label="$t('role.operating_time')">
						<div>
							<el-date-picker v-model="q.created_at.$gte" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('role.select_datetime')"></el-date-picker>
							-<el-date-picker v-model="q.created_at.$lt" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('role.select_datetime')"></el-date-picker>
						</div>
					</el-form-item>
					<el-form-item :label="$t('role.resource')">
						<el-select v-model="q.resource" :placeholder="$t('role.please_choose')">
							<el-option :label="$t('role.all')" :value=null></el-option>
							<el-option v-for="(resou, key) of resource_dict" :key="key" :label="resou" :value="key"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('role.resource_id')">
						<el-input v-model="q.resource_id" :placeholder="$t('role.resource_id')" prefix-icon="el-icon-edit"></el-input>
					</el-form-item>
					<el-form-item :label="$t('role.action')">
						<el-select v-model="q.action" :placeholder="$t('role.please_choose')">
							<el-option :label="$t('role.all')" :value=null></el-option>
							<el-option v-for="(act, key) of action_dict" :key="key" :label="act" :value="key"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="query">{{$t('role.search')}}</el-button>
						<el-button type="danger" @click="reload">{{$t('role.reset')}}</el-button>
					</el-form-item>
				</el-form>
			</el-collapse-item>
		</el-collapse>
		<el-table :data="listData.list" v-loading.body="listLoading" @sort-change="sortlist" element-loading-text="Loading" stripe border fit highlight-current-row>
			<el-table-column prop="id" label='ID' sortable width="100" align="center"></el-table-column>
			<el-table-column prop="rolename" :label='$t("role.name")' min-width="120"></el-table-column>
			<el-table-column prop="permissions" :label='$t("role.permission")' min-width="200">
				<template slot-scope="scope">{{getPermisions(scope.row.permissions)}}</template>
			</el-table-column>
			<el-table-column prop="enabled" :label='$t("role.status")' width="80" align="center">
				<template slot-scope="scope"> {{scope.row.enabled? $t("role.enable") : $t("role.disable")}} </template>
			</el-table-column>
			<el-table-column prop="updated_at" :label='$t("role.updated_at")' width="160">
			</el-table-column>
			<el-table-column :label='$t("role.action")' width="120" align="center">
				<template slot-scope="scope">
					<el-row :gutter="25">
						<el-col :span='8'>
							<el-button type="text"  plain title="编辑" size="small" v-if="$store.state.user.user_perms.includes('1302')" @click="edit(scope.row)">{{$t('role.edit')}}</el-button>
						</el-col>
						<el-col :span='8'>
							<el-button type="text" plain alt="删除" title="删除" size="small" v-if="$store.state.user.user_perms.includes('1303')" @click="remove(scope.row)">{{$t('role.delete')}}</el-button>
						</el-col>
					</el-row>
				</template>
			</el-table-column>
		</el-table>
		<div class="pagination">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="q.$page" :page-sizes="$store.state.app.pageSizeArr" :page-size="q.size" layout="total, sizes, prev, pager, next, jumper" :total="listData.total_count">
			</el-pagination>
		</div>
		<el-dialog title="内容详情" :visible.sync="showContent" width="30%">
			<ul>
				<li v-for="(cont, key) of DetailContent" :key="key">{{key}} => {{cont}}</li>
			</ul>
		</el-dialog>
		<update-role v-if="showUpdate" :showUpdate.sync="showUpdate" :roleDetailId="roleDetailId" :permTree="permTree" :permissions="permissions"></update-role>
	</div>
</template>

<script>
import updateRole from './updateRole';
import { getRoleList, getPermTree, getPermList, deleteRole } from '@/api/role';
import { mapState, mapActions } from 'vuex';

export default {
	components: { updateRole },
	data() {
		return {
			listData: {},
			q: { created_at: {}, $size: 30, $page: 1 },
			listLoading: true,
			showContent: false,
			DetailContent: false,
			resource_dict: {
				login: '登陆',
				single_mch: '商户管理',
				single_channel: '渠道管理',
				withdraw_channel: '下分通道管理',
				level_strategy: '分级策略管理',
				make_order_success: '补单'
			},
			action_dict: {
				1: '创建',
				2: '更新',
				3: '删除'
			},
			showUpdate: false,
			permList: {},
			roleStatusArray: ['活性', '不活跃'],
			roleDetailId: null,
			permissions: []
		}
	},
	created() {		 
		this.getList();
        this.listData = this.roles;
	},
	deactivated() {
		this.listLoading = false;
	},
	methods: {
		...mapActions('roles', {
			getAllRoles: 'getAll'
		}),   
		viewC(row) {
			this.showContent = true;
			this.DetailContent = JSON.parse(row.content);
		},
		query() {
			this.getList();
		},
		reload() {
			this.q = { created_at: {} };
			this.getList();
		},
		sortlist(sort) {
			this.q.$orderby = sort.prop; 
			this.getList();
		},
		handleSizeChange(val) {			 
			this.q.$size = val;
			this.getList();
		},
		handleCurrentChange(val) {
			this.q.$page = val; 
			this.getList();
		},
		getList() {
			let params = Object.assign({$orderby: 'id'},this.q);			
			// this.loading = true;			
			// this.getAllRoles(params);
			this.listLoading = true;
			getRoleList(params).then(res => { 
				if (res.status === 0) {
					this.listLoading = false;
                    this.listData = res.data;
				}
			});

			// this.listLoading = true;
			getPermList().then(res => {
				if (res.status === 0) {
					this.permList = res.data.list;
				}
			});
			
			
			// setInterval(() => {
			// if (!this.loading) {
			// 		this.listLoading = false;
			// 		this.listData = this.roles;
			// 	}
			// }, 100);
		},
		addDelimeter(data) {
			data = data.toString();
			data = data.replace(/ /g, '');
			data = data.replace(/,/g, '|');
			return data;
		},
		edit(row) {
			this.showUpdate = true;
			this.roleDetailId = row.id;
			this.permissions = this.clean(row.permissions);
		},
		remove(row) {
			this.$confirm(this.$t('role.confirm_remove') + `${row.rolename}?`, this.$t('role.remove_role'), {
				confirmButtonText: this.$t('role.ok'),
				cancelButtonText: this.$t('role.cancel'),
				type: 'warning'
			})
				.then(() => {
					deleteRole(row.id).then(res => {
						if (res.status === 0) {
							this.$message({
								type: 'success',
								message: `${row.rolename}` + this.$t('role.remove_success')
							});							 
							this.getList();
						}
					});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: this.$t('role.cancelled')
					});
				});
		},
		add() {
			this.permissions = [];
			this.roleDetailId = null;
			this.showUpdate = true;
		},
		getPermTree() {
			getPermTree().then(res => {
				if (res.status === 0) {
					this.permTree = res.data; 
				}
			});
		},
		getPermisions(pems) { 
			let roleDescs = [];
			if(pems.length > 0) {	
				pems.forEach(element => {					
					if(this.permList.length > 0) {
						this.permList.forEach(item => {							
							if(item.id.toString() === element) {
								roleDescs.push(item.desc);	
							}
						})
					}
				});
			}
			return roleDescs;
		},
		clean(permissions) {  	
			let item = [];	
            if(permissions.length > 0) {
                permissions.forEach(element => { 
                    if(element) {
                        item.push(parseInt(element));
                    }
                }); 
			}
			return item;
		}
	},
	computed: {
		...mapState({
			roles: state => state.roles.roles,
			loading: state => state.roles.loading
		})
	},
	watch: {
		showUpdate() {
			if (!this.showUpdate) {				
				this.getList();
			}
		}
	},
	beforeMount() {
		this.getPermTree();
	}
}

export const enRole = {
	// General
	click_filter: 'Click to filter',

	// Table
	id: 'ID',
	name: 'Role Name',
	permission: 'Permission',
	status: 'Status',	
	enable: 'Enabled',
	disable: 'Disabled',
	updated_at: 'Updated at',
	action: 'Action',

	// Search and Filter
	operator: 'Operator',
	operating_time: 'Operating Time',
	select_datetime: 'Select Date and Time',
	resource: 'Resource',
	please_choose: 'Please choose',
	all: 'All',
	resource_id: 'Resource ID',

	// Action Button
	add: 'Add',
	edit: 'Edit',
	delete: 'Delete',
	search: 'Search',
	reset: 'Reset',

	// Messages
	confirm_remove: 'Are you sure you want to delete role ',
	remove_role: 'Delete Role',
	ok: 'OK',
	cancel: 'Cancel',
	cancelled: 'Cancelled',
	remove_success: ' has been successfully deleted!'
}

export const zhRole = {
	// General
	click_filter: '点击筛选',

	// Table
	id: 'ID',
	name: '角色名称',
	permission: '权限',
	status: '状态',
	enable: '可用',
	disable: '禁用',
	updated_at: '更新于',
	action: '操作',

	// Search and Filter
	operator: '操作者',
	operating_time: '操作时间',
	select_datetime: '选择日期时间',
	resource: '资源',
	please_choose: '请选择',
	all: '所有',
	resource_id: '资源ID',

	// Action Button
	add: '新增角色',
	edit: '编辑',
	delete: '删除',
	search: '查询',
	reset: '重置',

	// Messages
	confirm_remove: '确认删除角色吗',
	remove_role: '删除角色',
	ok: '确定',
	cancel: '取消',
	cancelled: '已取消删除',
	remove_success: '成功删除!'
}

</script>
